package net.servlet;

import cn.miao.framework.util.Cache;
import cn.miao.framework.util.DateUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.math.RandomUtils;

public class UploadServlet2 extends HttpServlet
{
  private String uploadPath;
  private Map<String, String> params = new HashMap();

  public void destroy()
  {
    super.destroy();
  }

  protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    super.doDelete(req, resp);
  }

  protected void doPut(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    super.doPut(req, resp);
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    doPost(request, response);
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    response.setContentType("text/javascript");
    this.params.clear();
    String path = request.getParameter("path");
    String callback = request.getParameter("callback");

    String mid = request.getParameter("username");
	if(mid == null){
		mid="username";
	}
    setUploadPath(mid);
    try {
      uploadFiles(request, response);
      this.params.put("result", "success");
    } catch (Exception e) {
      this.params.put("result", "fail");
    }
    if ((callback == null) || (callback.length() == 0))
      response.getWriter().print(JSONObject.fromObject(this.params).toString());
    else
      response.getWriter().print(callback + "(" + JSONObject.fromObject(this.params).toString() + ");");
  }

  private void setUploadPath(String path)
  {
    
	String prjPath = getServletContext().getRealPath("/");
	String _prjname = getServletContext().getContextPath();
	String prjname = _prjname.replaceAll("/", "");
	uploadPath = prjPath.replace(prjname, "ROOT") + "photos/" + path + "/";
	File uploadFile = new File(uploadPath);
	if (!uploadFile.exists()) {
		uploadFile.mkdirs();
}
  }

  private void uploadFiles(HttpServletRequest request, HttpServletResponse response)
    throws UnsupportedEncodingException
  {
    String encoding = request.getCharacterEncoding();
    try
    {
      DiskFileItemFactory factory = new DiskFileItemFactory();

      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setHeaderEncoding(encoding);

      List items = upload.parseRequest(request);
      Iterator i = items.iterator();
      while (i.hasNext()) {
        FileItem fi = (FileItem)i.next();
        String fileName = fi.getName();
        if (fileName != null) {
          File fullFile = new File(fi.getName());
          File savedFile = new File(this.uploadPath, fullFile.getName());
          fi.write(savedFile);
          if (fileName.indexOf('\\') > -1) {
            fileName = fileName.substring(fileName
              .lastIndexOf('\\') + 1);
          }
          InputStream inputStream = new FileInputStream(this.uploadPath + 
            fileName);
          inputStream.close();
//          String newFileName = "";
//          if (Cache.newfileRule == null) {
//            newFileName = DateUtil.getToday("yyyyMMddHHmmss");
//          }
//          else if (Cache.newfileRule.contains("date")) {
//            String dateRule = Cache.newfileRule.split(":")[1];
//            newFileName = DateUtil.getToday(dateRule);
//          } else {
//            newFileName = String.valueOf(RandomUtils.nextLong());
//          }

//          newFileName = newFileName + fileName.substring(fileName.lastIndexOf('.'));
//          this.params.put("orgname", fileName);
//          this.params.put("filename", newFileName);

//          savedFile.renameTo(new File(this.uploadPath + newFileName));
        } else {
          this.params.put(fi.getFieldName(), fi.getString(encoding));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}